package com.adingxiong.cft.util;

import com.adingxiong.cft.config.FastdfsProperties;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.domain.fdfs.ThumbImageConfig;
import com.github.tobato.fastdfs.domain.proto.storage.DownloadByteArray;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.github.tobato.fastdfs.service.TrackerClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;

/**
 * @ClassName FastDFSClient
 * @Description TODO
 * @Author xiongchao
 * @Date 2020/9/8 13:40
 **/
@Component
public class FastDFSClient {

    private Logger log = LoggerFactory.getLogger(FastDFSClient.class);

    @Autowired
    FastdfsProperties fastdfsProperties;


    @Autowired
    private FastFileStorageClient storageClient;

    //创建缩略图的
    @Autowired
    private ThumbImageConfig imageConfig;

    @Autowired
    private TrackerClient trackerClient;


    /**
     * 简单文件上传
     * @param file
     * @return
     */
    public  String upload (MultipartFile file){
        String fileName  = file.getOriginalFilename();
        try {
            InputStream inputStream= file.getInputStream();

            long size = file.getSize();

            StorePath path = storageClient.uploadFile(inputStream,size,fileName.substring(fileName.lastIndexOf(".")+ 1), null);

            return getResAccessUrl(path);
        } catch (IOException e) {
            e.printStackTrace();
            log.error(e.toString());
            return null;
        }
    }

    /**
     * 删除指定文件
     * @param url
     */
    public  void delFile (String url){
        storageClient.deleteFile(url);
    }


    /**
     * 文件下载
     * @param fileUrl
     * @return
     * @throws IOException
     */
    public byte[] downloadFile(String fileUrl) throws IOException {
        fileUrl = fileUrl.replaceAll(fastdfsProperties.getWebServerUrl(),"");
        String group = fileUrl.substring(0, fileUrl.indexOf("/"));
        String path = fileUrl.substring(fileUrl.indexOf("/") + 1);
        DownloadByteArray downloadByteArray = new DownloadByteArray();
        byte[] bytes = storageClient.downloadFile(group,path, downloadByteArray);
        return bytes;
    }
    /**
     * 获取文件路径
     * @param path
     * @return
     */
    private  String getResAccessUrl(StorePath path) {
        String fileUrl = "http://" +  fastdfsProperties.getReqHost() + ":" +  fastdfsProperties.getReqPort() +  "/" + path.getFullPath();
        return fileUrl;
    }
}
